<?php

namespace app\api\controller;

use app\facade\Redis;
use rsa\Rsa;
use app\models\{User as Users, Holiday, Address, Message, Region, AreaPrice, CateSons, GarbageCate, Riderlist, Order, Orderlog, PartnerApply, RiderStreet, IntergralLog, Wechat};
use think\Facade\Config as Configs;
use app\facade\Mns;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;

class User extends Base
{
    public function wxpay()
    {
        $ordersn = time() . rand(1, 1000);
        $payment = [
            'pay_title' => '订单编号:' . $ordersn,
            'payment_id' =>  $ordersn . rand(1000, 9999),
            'money' => 0.01,
            'ip' => $this->request->ip(),
            'user_id' => 0,
            'params' => json_encode(['trade_type' => 'JSAPI'], true)
        ];
        $list = (new Wechat())->pay($payment);
        if ($list['status'] == true) {
            $res = (new Payment())->save([
                'paymentid' => $payment['payment_id'],
                'orderid' => $result['id'],
                'money' => $payment['money']
            ]);
            if ($res) {
                $this->result($list, 0, '获取成功');
            }
        }
        $this->result([], 1, '操作失败，请重试');
    }

    public function info()
    {
        $list = (new Users())->field('openid,unionid,token,created,password,updated', true)->where('id', $this->request->user_id)->find();
        $list['total'] = (new Order())->where(['user_id' => $list['id'], 'status' => 3])->sum('total');
        $list['city_text'] = (new Region())->where(['area_code' => $list['cityid']])->value('name');
        $list['area_text'] = (new Region())->where(['area_code' => $list['areaid']])->value('name');
        $this->result($list, 0, '获取成功');
    }

    public function invita()
    {
        $list = (new Users())->field('id,nickname,logo,created')->where('pid', $this->request->user_id)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['money'] = (new Order())->where(['user_id' => $lists['id'], 'status' => 3])->sum('total');
        }
        $this->result($list, 0, '获取成功');
    }


    public function Setmobile()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'iv' => 'require',
            'encryptedData' => 'require',
        ], [
            'iv.require' => 'IV不能为空',
            'encryptedData.require' => 'encryptedData不能为空',

        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $config = config('wechat.');
        $app = Factory::miniProgram($config);
        $user = (new Users())->where('id', $this->request->user_id)->find();
        try {
            $decryptedData = $app->encryptor->decryptData($user['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, '操作失败,请删除小程序重新授权');
        }
        if (!empty($decryptedData['phoneNumber'])) {
            $data['mobile'] = $decryptedData['phoneNumber'];
            $res = (new Users())->where('id', $this->request->user_id)->update(['mobile' => $data['mobile']]);
            if ($res) {
                $this->result(['mobile' => $data['mobile']], 0, '授权成功');
            }
        }
        $this->result([], 1, '授权失败');
    }

    public function bindcode()
    {
        $code = $this->request->get('code/d', 0);
        if (empty($code)) {
            $this->result([], 1, '请输入正确邀请码');
        }
        if ($this->request->user['pid'] > 0) {
            $this->result([], 1, '用户已绑定邀请人');
        }
        $codeuser = (new Users())->where('code', $code)->find();
        if (empty($codeuser)) {
            $this->result([], 1, '邀请人不存在');
        }
        if ($codeuser['id'] == $this->request->user_id) {
            $this->result([], 1, '邀请人不能是自己');
        }
        $res = (new Users())->where('id', $this->request->user_id)->update(['pid' => $codeuser['id']]);
        if ($res) {
            $this->result([], 0, '绑定成功');
        }
        $this->result([], 1, '绑定失败');
    }

    public function qrcode()
    {
        $name = 'appcode' . $this->request->user_id . '.png';
        $qcode = url('/wechat/' . $name, '', '', true);
        $path =  $_SERVER['DOCUMENT_ROOT'] . "/wechat/";
        if (!file_exists($path . $name)) {
            $user = (new Users())->where('id', $this->request->user_id)->find();
            $config = config('wechat.');
            $app = Factory::miniProgram($config);
            $rm = $app->app_code->getUnlimit('invite=' . $user['code'], [
                'page'  => '',
                'width' => 600,
            ]);
            if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $rm->save($path, $name);
            }
        }
        $this->result($qcode, 0, '获取成功');
    }

    //微信小程序账号登录|注册
    public function login2()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
        ], [
            'code.require' => '微信授权码不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        Log::write($data, 'invite');
        $config = config('wechat.');
        $app = Factory::miniProgram($config);
        $res = $app->auth->session($data['code']);
        $time = $config['tokenExpireHours'];
        try {
            $decryptedData = $app->encryptor->decryptData($res['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, $e->getMessage());
        }
        if (!empty($res['unionid']) && !empty($res['session_key'])) {
            $user = (new Users())->where('unionid', $res['unionid'])->find();
            if (!empty($user)) {
                $pid = $user['pid'];
                if (!empty($data['invite']) && $user['pid'] <= 0) {
                    $pid = (new Users())->where('code', $data['invite'])->value('id');
                    $pid = $pid ?? $user['pid'];
                    if ($pid == $user['id']) {
                        $pid = 0;
                    }
                }

                $savearr = [
                    'session_key' => $res['session_key'],
                    'logo' => $decryptedData['avatarUrl'] ?? '',
                    'nickname' => $decryptedData['nickName'] ?? '',
                    'pid' => $pid,
                    'sex' => $decryptedData['gender'] ?? 0,
                ];
                $rs = (new Users())->where('unionid', $res['unionid'])->update($savearr);
                Redis::setex($res['session_key'], $time, $user['id']);
            } else {
                $pid = 0;
                if (!empty($data['invite'])) {
                    $pid = (new Users())->where('code', $data['invite'])->value('id');
                    $pid = $pid ?? 0;
                }
                $savearr = [
                    'session_key' => $res['session_key'],
                    'openid' => $res['openid'],
                    'pid' => $pid,
                    'code' => recode(new Users()),
                    'mobile' => $decryptedData['mobile'] ?? '',
                    'logo' => $decryptedData['avatarUrl'] ?? '',
                    'unionid' => $res['unionid'] ?? '',
                    'nickname' => $decryptedData['nickName'] ?? '',
                    'sex' => $decryptedData['gender'] ?? 0,
                ];
                try {
                    $rs = (new Users())->insertGetId($savearr);
                } catch (\Exception $e) {
                    Log::write($savearr, 'weichats');
                    Log::write($e->getMessage(), 'weichats');
                    $this->result([], 1, '操作失败,请联系管理员');
                }
                if ($rs) {
                    Redis::setex($res['session_key'], $time, $rs);
                }
            }
            $this->result(['token' => $res['session_key'], 'expire' => $time], 0, '登录成功');
        } else {
            $this->result([], 1, '登录失败');
        }
    }

    //微信APP账号登录|注册
    public function login3()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'unionid' => 'require',
            'nickname' => 'require',
            'logo' => 'require',
        ], [
            'unionid.require' => '微信授权码不能为空',
            'nickname.require' => '昵称不能为空',
            'logo.require' => '头像不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (!empty($data['unionid'])) {
            $user = (new Users())->where('unionid', $data['unionid'])->find();
            $res['session_key'] = md5(time() . md5($data['unionid']));
            $config = config('wechat3.');
            $time = $config['tokenExpireHours'];
            if (!empty($user)) {
                Redis::setex($res['session_key'], $time, $user['id']);
            } else {
                $pid = 0;
                if (!empty($data['invite'])) {
                    $pid = (new Users())->where('code', $data['invite'])->value('id');
                    $pid = $pid ?? 0;
                }
                $savearr = [
                    'openid' => $data['openid'] ?? '',
                    'unionid' => $data['unionid'] ?? '',
                    'pid' => $pid,
                    'code' => recode(new Users()),
                    'logo' => $data['logo'] ?? '',
                    'type' => 2,
                    'nickname' => $data['nickname'] ?? ''
                ];
                try {
                    $rs = (new Users())->insertGetId($savearr);
                } catch (\Exception $e) {
                    Log::write($savearr, 'weichats');
                    Log::write($e->getMessage(), 'weichats');
                    Log::write('==============分割线=============', 'weichats');
                    $this->result([], 1, '操作失败,请联系管理员');
                }
                if ($rs) {
                    Redis::setex($res['session_key'], $time, $rs);
                }
            }
            $this->result(['token' => $res['session_key'], 'expire' => $time], 0, '登录成功');
        } else {
            $this->result([], 1, '登录失败');
        }
    }


    public function nearbyRider()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'lon' => 'require',
            'lat' => 'require'
        ], [
            'lon.require' => '地址坐标不能为空',
            'lat.require' => '地址坐标不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $sql = "SELECT  
        mobile,name,riderlon,riderlat,(  
          6371 * acos (  
            cos ( radians(" . $data['lat'] . ") )  
            * cos( radians( riderlat ) )  
            * cos( radians( riderlon ) - radians(" . $data['lon'] . ") )  
            + sin ( radians(" . $data['lat'] . ") )  
            * sin( radians( riderlat ) )  
          )  
        ) AS distance  
      FROM tb_riderlist
      HAVING distance < 200
      ORDER BY distance";
        $riderlist = Db::query($sql);
        foreach ($riderlist as &$list) {
            $list['distance'] = round($list['distance'], 2);
        }
        $this->result($riderlist, 0, '获取成功');
    }

    public function address()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'street' => 'require',
                'address' => 'require',
                'lon' => 'require',
                'lat' => 'require',
                'is_default' => 'require|in:1,2'
            ], [
                'name.require' => '联系人不能为空',
                'mobile.require' => '联系电话不能为空',
                'street.require' => '街道ID不能为空',
                'address.require' => '详细地址不能为空',
                'lon.require' => '地址坐标不能为空',
                'lat.require' => '地址坐标不能为空',
                'is_default.require' => '地址类型不能为空',
                'is_default.in' => '地址类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                $this->result([], 1, '联系电话格式不正确');
            }
            $street = (new Region())->where(['id' => $data['street'], 'level' => 4])->find();
            if (empty($street)) {
                $this->result([], 1, '街道ID错误');
            }
            $area = (new Region())->where(['id' => $street['parent_id'], 'level' => 3])->find();
            if (empty($area)) {
                $this->result([], 1, '区域编号错误');
            }
            $data['area'] = $area['area_code'];
            $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
            if (empty($city)) {
                $this->result([], 1, '城市编号错误');
            }
            $province = (new Region())->where(['id' => $city['parent_id'], 'level' => 1])->find();
            if (empty($province)) {
                $this->result([], 1, '省份编号错误');
            }
            if (!empty($data['id'])) {
                $list = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['id']])->find();
                if (empty($list)) {
                    $this->result([], 1, '地址信息不存在');
                }
            }
            $data['user_id'] = $this->request->user_id;
            $data['province'] = $province['area_code'];
            $data['city'] = $city['area_code'];
            Db::startTrans();
            try {
                (new Address())->where('user_id', $this->request->user_id)->update(['is_default' => 1]);
                if (!empty($data['id'])) {
                    (new Address())->allowfield(true)->save($data, ['id' => $data['id']]);
                } else {
                    (new Address())->allowfield(true)->save($data);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败');
            }
            $this->result([], 0, '操作成功');
        } else {
            $list = (new Address())->where('user_id', $this->request->user_id)->order('is_default desc')->select();
            $key = '6YGBZ-3CQWP-MAQDB-LNPC4-RZZ27-FYFM4';
            foreach ($list as $lists) {
                $lists['province_text'] = (new Region())->where(['area_code' => $lists['province']])->value('name');
                $lists['city_text'] = (new Region())->where(['area_code' => $lists['city']])->value('name');
                $lists['area_text'] = (new Region())->where(['area_code' => $lists['area']])->value('name');
                $lists['street_text'] = (new Region())->where(['id' => $lists['street']])->value('name');
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function address_detail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Address())->where(['id' => $id, 'user_id' => $this->request->user_id])->find();
        if (!empty($list)) {
            $list['province_text'] = (new Region())->where(['area_code' => $list['province']])->value('name');
            $list['city_text'] = (new Region())->where(['area_code' => $list['city']])->value('name');
            $list['area_text'] = (new Region())->where(['area_code' => $list['area']])->value('name');
            $list['street_text'] = (new Region())->where(['id' => $list['street']])->value('name');
        } else {
            $this->result([], 1, '获取失败');
        }
        $this->result($list, 0, '获取成功');
    }

    public function address_del()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Address())->where(['id' => $id, 'user_id' => $this->request->user_id])->find();
        if (!$list) {
            $this->result([], 1, '地址不存在');
        }
        $res = (new Address())->where('id', $list['id'])->delete();
        if ($res) {
            $this->result([], 0, '删除成功');
        }
        $this->result([], 1, '删除失败，请重试');
    }

    public function getstreet()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Region())->where(['area_code' =>  $id, 'level' => 4])->field('id,name')->select();
        $this->result($list, 0, '获取成功');
    }

    public function garbagecate()
    {
        $list = (new GarbageCate())->field('id,name,icon,url,msgs')->select();
        $this->result($list, 0, '获取成功');
    }

    public function areaprice()
    {
        $areaid = $this->request->get('areaid/d', 0);
        $cat = $this->request->get('cat/d', 0);
        $abc = $this->request->get('abc/d', 0);
        if (empty($areaid)) {
            $this->result([], 0, '获取成功');
        }
        //通过街道获取区域id
        $areatops = (new Region())->where('id', $areaid)->find();
        $areatop = $areatops['area_code'] ?? 0;
        //通过区域获取城市ID
        $citytops = (new Region())->where(['id' => $areatops['parent_id']])->find();
        $citytop =  (new Region())->where(['id' => $citytops['parent_id']])->value('area_code');
        $where = [
            'streetid' => $areaid,
            'cate' => $cat
        ];
        $whereOr = [
            'areaid' => $areatop,
            'streetid' => 0,
            'cate' => $cat
        ];
        $whereor2 = [
            'areaid' => 0,
            'streetid' => 0,
            'cate' => $cat
        ];
        $list = (new CateSons());
        $list = $list->where($where)->whereOr(function ($query) use ($whereOr) {
            $query->where($whereOr);
        })->whereOr(function ($query1) use ($whereor2) {
            $query1->where($whereor2);
        })->field('cate,created', true)->select();
        $type = Configs::get('config.ordertype');
        foreach ($list as $k => $lists) {
            $areaprice = (new AreaPrice())->where('streetid', $areaid)->where('catsonsid', $lists['id'])->find();
            if (empty($areaprice)) {
                $getareaid = (new Region())->where('id', $areaid)->value('area_code');
                $areaprice = (new AreaPrice())->where(['areaid' => $getareaid, 'streetid' => 0])->where('catsonsid', $lists['id'])->find();
            }
            $lists['price'] = !empty($areaprice['price']) ? $areaprice['price'] : 0;
            $lists['unmit'] = $areaprice['unmit'] ?? '公斤';
            $typp = [];
            foreach ($type as $k => $types) {
                $typp[$k] = $types;
                $typp[$k]['name'] = $types['name'] . $lists['unmit'];
            }
            $lists['type'] = array_merge($typp);
        }
        $this->result($list, 0, '获取成功');
    }

    public function getprice()
    {
        $streetid = $this->request->get('areaid/d', 0);
        $cat = $this->request->get('cat/d', 0);
        $result['min'] = 0;
        $result['max'] = 0;
        //通过街道获取区域id
        $areatops = (new Region())->where('id', $streetid)->find();
        $areatop = $areatops['area_code'] ?? 0;
        //通过区域获取城市ID
        $citytop = (new Region())->where(['id' => $areatops['parent_id']])->value('area_code');
        $where = [
            'streetid' => $streetid,
            'cate' => $cat
        ];
        $whereOr = [
            'areaid' => $areatop,
            'streetid' => 0,
            'cate' => $cat
        ];
        $whereor2 = [
            'areaid' => 0,
            'streetid' => 0,
            'cate' => $cat
        ];
        $list = (new CateSons())->where($where)->whereOr(function ($query) use ($whereOr) {
            $query->where($whereOr);
        })->whereOr(function ($query1) use ($whereor2) {
            $query1->where($whereor2);
        })->field('cate,created', true)->select();
        foreach ($list as $lists) {
            if ($citytop == 130200 && in_array($lists['id'], [8, 9, 12, 14])) {
                unset($lists);
            }
            $price = (new AreaPrice())->where('streetid', $streetid)->where('catsonsid', $lists['id'])->value('price') ?? 0;
            if (empty($price)) {
                $areaid = (new Region())->where('id', $streetid)->value('area_code') ?? 0;
                $price = (new AreaPrice())->where('areaid', $areaid)->where('catsonsid', $lists['id'])->value('price') ?? 0;
            }
            if ($price > $result['max'] && !empty($price)) {
                $result['max'] = $price;
            }
            if (($result['min'] <= 0 || $price < $result['min']) && !empty($price)) {
                $result['min'] = $price;
            }
        }
        $this->result($result, 0, '获取成功');
    }

    public function order()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'addressid' => 'require',
                // 'appointment' => 'require',
                'data' => 'require',
                'ispublic' => 'require|in:1,2',
            ], [
                'addressid.require' => '地址id不能为空',
                // 'appointment.require' => '预约时间不能为空',
                'data.require' => '数据不能为空',
                'ispublic.require' => '类型不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            // if (!strtotime($data['appointment'])) {
            //     $this->result([], 1, '时间格式错误');
            // }
            // $data['appointment'] = ;
            // if ($data['appointment'] < date('Y-m-d H:i:s', time())) {
            //     $this->result([], 1, '预约时间不能低于当前时间');
            // }
            $data['data'] = json_decode($data['data'], true);
            if (empty($data['data'])) {
                $this->result([], 1, '数据格式错误');
            }
            //判断地址是否正确
            $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
            if (empty($address)) {
                $this->result([], 1, '地址错误');
            }
            //判断地区是否停止下单
            $holiday = (new Holiday())->where('areaid', $address['area'])->find();
            if (!empty($holiday)) {
                $this->result([], 1, $holiday['msg']);
            }
            //判断当前区域是否有骑手 
            $RiderStreet = (new RiderStreet())->where(['street' => $address['street'], 'status' => 2])->column('riderid');
            if (count($RiderStreet) <= 0) {
                $this->result([], 1, '地址区域没有骑手');
            }
            $RiderList = (new RiderList())->where(['id' => $RiderStreet, 'status' => 1])->column('user_id');
            if (count($RiderList) <= 0) {
                $this->result([], 1, '地址区域骑手繁忙，请稍后再下单');
            }
            $ordersn = time() . rand(11111, 99999);
            $orderdata = [
                'user_id' => $this->request->user_id,
                'appointment' => $data['appointment'] ?? date('Y-m-d H:i:s'),
                'name' => $address['name'],
                'mobile' => $address['mobile'],
                'province' => $address['province'],
                'city' =>  $address['city'],
                'area' =>  $address['area'],
                'street' =>  $address['street'],
                'address' =>  $address['address'],
                'posaddress' => $address['posaddress'] ?? '',
                'lon' =>  $address['lon'],
                'lat' =>  $address['lat'],
                'status' => 1,
                'ordersn' => $ordersn,
                'info' => !empty($data['info']) ? $data['info'] : '',
            ];
            $orderlog = [];
            foreach ($data['data'] as $datas) {
                if (empty($datas['type'])) {
                    $datas['type'] = 0;
                }
                if (empty($datas['id'])) {
                    $this->result([], 1, '数据参数错误');
                }
                $CateSons = (new CateSons())->where(['id' => $datas['id']])->find();
                if (empty($CateSons)) {
                    $this->result([], 1, '分类信息不存在');
                }
                $list = (new AreaPrice())->where(['catsonsid' => $CateSons['id'], 'streetid' => $address['street']])->find();
                if (empty($list)) {
                    $list = (new AreaPrice())->where(['catsonsid' => $CateSons['id'], 'areaid' => $address['area']])->find();
                }
                if (empty($list)) {
                    $this->result([], 1, '回收街道、村镇价格为0，请重新选择');
                }
                $orderlog[] = [
                    'ordersn' => $ordersn,
                    'areapriceid' => $list['id'],
                    'money' =>  $list['price'],
                    'type' => $datas['type'],
                    'icon' => $CateSons['icon'],
                    'unmit' => $list['unmit'],
                    'name' => $CateSons['name']
                ];
            }
            Db::startTrans();
            try {
                (new Order())->allowfield(true)->save($orderdata);
                (new Orderlog())->allowfield(true)->saveAll($orderlog);
                Db::commit();
            } catch (\Exception $exception) {
                dump($exception->getMessage());
                Db::rollback();
                $this->result([], 1, '操作失败');
            }
            $this->result([], 0, '操作成功');
        } else {
            $data = $this->request->get();
            $validate = new Validate([
                'addressid' => 'require'
            ], [
                'addressid.require' => '地址id不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //判断地址是否正确
            $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
            if (empty($address)) {
                $this->result([], 1, '地址错误');
            }
            //判断地区是否停止下单
            $holiday = (new Holiday())->where('areaid', $address['area'])->find();
            if (!empty($holiday)) {
                $this->result([], 1, $holiday['msg']);
            }
            //是否存在合伙人
            $areauser = (new Users())->where('areaid', $address['area'])->find();
            if (empty($address)) {
                $this->result([], 1, '提示：此城市暂未开通合伙人，合作请致电400-267-6918');
            }
            //判断当前区域是否有骑手
            $RiderStreet = (new RiderStreet())->where(['street' => $address['street'], 'status' => 2])->column('riderid');
            if (count($RiderStreet) <= 0) {
                $this->result([], 1, '地址区域没有骑手');
            }
            $RiderList = (new RiderList())->where(['id' => $RiderStreet, 'status' => 1])->column('user_id');
            if (count($RiderList) <= 0) {
                $this->result([], 1, '地址区域骑手繁忙，请稍后再下单');
            }
            $this->result([], 0, '操作成功');
        }
    }

    public function orderlist()
    {
        $list = (new Order())->order('id desc');
        $status = $this->request->get('status/d', 0);
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        $list = $list->field('id,ordersn,status,created,appointment,province,city,area,street,address,lon,lat,total,info,ispublic,orders_id,mobile,posaddress,endtime')->where('user_id', $this->request->user_id)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['province_text'] = (new Region())->where(['area_code' => $lists['province']])->value('name');
            $lists['city_text'] = (new Region())->where(['area_code' => $lists['city']])->value('name');
            $lists['area_text'] = (new Region())->where(['area_code' => $lists['area']])->value('name');
            $lists['street_text'] = (new Region())->where(['id' => $lists['street']])->value('name');
            $lists['orderlog'] = (new Orderlog())->where('ordersn', $lists['ordersn'])->field('id,name,icon,type,money,unmit')->select();
            $min = 0;
            $max = 0;
            foreach ($lists['orderlog'] as $orderlog) {
                $configs = Configs::get('config.ordertype.' . $orderlog['type']);
                $orderlog['ordertype'] =  $configs['name'] . $orderlog['unmit'];
                if ($lists['status'] != 3) {
                    $min += $orderlog['money'] *  $configs['mintotal'];
                    $max += $orderlog['money'] *  $configs['maxtotal'];
                }
            }
            $lists['order_mobile'] = '';
            if ($lists['orders_id'] > 0) {
                $lists['order_mobile'] = (new Riderlist())->where('id', $lists['orders_id'])->value('mobile');
            }
            if ($lists['status'] != 3) {
                $lists['total'] = $min . '~' . $max;
            }
            if ($lists['status'] == 1) {
                $lists['status_text'] = '待接单';
            }
            if ($lists['status'] == 2) {
                $lists['status_text'] = '已接单';
            }
            if ($lists['status'] == 3) {
                $lists['status_text'] = '已完成';
            }
            if ($lists['status'] == 4) {
                $lists['status_text'] = '已取消';
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function ordercancel()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where(['id' => $id, 'user_id' => $this->request->user_id])->find();
        if (empty($list)) {
            $this->result([], 1, '订单数据不存在');
        }
        if ($list['status'] != 1) {
            $this->result([], 1, '订单不可取消');
        }
        $res = (new Order())->where(['id' => $id, 'user_id' => $this->request->user_id, 'status' => 1])->update(['status' => 4]);
        if ($res) {
            $this->result([], 1, '取消成功');
        }
        $this->result([], 1, '取消失败，请重试');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $lists = (new Order())->where(['id' => $id, 'user_id' => $this->request->user_id])
            ->field('id,ordersn,status,orders_id,created,appointment,province,city,area,street,address,lon,lat,total,info,ispublic,mobile,riderlon,riderlat,posaddress,endtime')->find();
        if (empty($lists)) {
            $this->result([], 1, '获取失败');
        }
        $rider = (new Riderlist())->where('id', $lists['orders_id'])->find();
        $lists['riderlon'] = $rider['riderlon'];
        $lists['riderlat'] = $rider['riderlat'];
        $lists['province_text'] = (new Region())->where(['area_code' => $lists['province']])->value('name');
        $lists['city_text'] = (new Region())->where(['area_code' => $lists['city']])->value('name');
        $lists['area_text'] = (new Region())->where(['area_code' => $lists['area']])->value('name');
        $lists['street_text'] = (new Region())->where(['id' => $lists['street']])->value('name');
        $lists['orderlog'] = (new Orderlog())->where('ordersn', $lists['ordersn'])->field('id,name,icon,type,money,unmit')->select();
        if ($lists['orders_id'] > 0) {
            $lists['order_mobile'] = (new Riderlist())->where('id', $lists['orders_id'])->value('mobile');
        } else {
            $lists['order_mobile'] = '';
        }
        $min = 0;
        $max = 0;
        foreach ($lists['orderlog'] as $orderlog) {
            $configs = Configs::get('config.ordertype.' . $orderlog['type']);
            $orderlog['ordertype'] =  $configs['name'] . $orderlog['unmit'];
            if ($lists['status'] != 3) {
                $min += $orderlog['money'] *  $configs['mintotal'];
                $max += $orderlog['money'] *  $configs['maxtotal'];
            }
        }
        if ($lists['status'] != 3) {
            $lists['total'] = $min . '~' . $max;
        }
        if ($lists['status'] == 1) {
            $lists['status_text'] = '待接单';
        }
        if ($lists['status'] == 2) {
            $lists['status_text'] = '已接单';
        }
        if ($lists['status'] == 3) {
            $lists['status_text'] = '已完成';
        }
        if ($lists['status'] == 4) {
            $lists['status_text'] = '已取消';
        }
        $this->result($lists, 0, '获取成功');
    }

    public function partnerApply()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'province' => 'require',
                'city' => 'require',
                'area' => 'require',
                'type' => 'require|in:1,2',
                'mobile' => 'require',
                'info' => 'require'
            ], [
                'province.require' => '省份ID不能为空',
                'city.require' => '城市ID不能为空',
                'area.require' => '区域ID不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型错误',
                'mobile.require' => '手机不能为空',
                'info.require' => '备注不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                $this->result([], 1, '联系电话格式不正确');
            }
            $user = (new Users())->where('id', $this->request->user_id)->find();
            if ($user['cityid'] ||  $user['areaid']) {
                $this->result([], 1, '您已经是合伙人，无法重复申请');
            }
            //判断是否存在待审核信息
            $apply = (new PartnerApply())->where(['status' => 1, 'user_id' => $this->request->user_id])->find();
            if (!empty($apply)) {
                $this->result([], 1, '您有待审核的申请，请等待申请完成');
            }
            //判断区域是否已存在
            if ($data['type'] == 1) {
                $cityuser = (new Users())->where('cityid', $data['city'])->find();
                if (!empty($cityuser)) {
                    $this->result([], 1, '该城市已有合伙人');
                }
            }
            $areauser = (new Users())->where('areaid', $data['area'])->find();
            if (!empty($areauser)) {
                $this->result([], 1, '该区域已有合伙人');
            }
            //查省市区是否存在
            $province = (new Region())->where(['area_code' => $data['province'], 'level' => 1])->find();
            if (empty($province)) {
                $this->result([], 1, '省份编号错误');
            }
            $city = (new Region())->where(['area_code' => $data['city'], 'level' => 2, 'parent_id' => $province['id']])->find();
            if (empty($city)) {
                $this->result([], 1, '城市编号错误');
            }
            $area = (new Region())->where(['area_code' => $data['area'], 'level' => 3, 'parent_id' => $city['id']])->find();
            if (empty($area)) {
                $this->result([], 1, '区域编号错误');
            }
            $data['user_id'] = $this->request->user_id;
            $res = (new PartnerApply())->allowfield(true)->save($data);
            if ($res) {
                $this->result([], 0, '申请成功，等待审核');
            }
            $this->result([], 1, '申请失败，请重试');
        } else {
            $list = (new PartnerApply())->field('user_id', true)->where(['status' => 1, 'user_id' => $this->request->user_id])->find();
            if (!empty($list)) {
                $list['province_text'] = (new Region())->where(['area_code' => $list['province']])->value('name');
                $list['city_text'] = (new Region())->where(['area_code' => $list['city']])->value('name');
                $list['area_text'] = (new Region())->where(['area_code' => $list['area']])->value('name');
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function integral()
    {
        $list = (new IntergralLog())->order('id desc');
        $config = Configs::get('config.intertype');
        $list = $list->where(['user_id' =>  $this->request->user_id])
            ->field('type,money,created')
            ->paginate(20, false, ['query' => $this->request->param()])->each(function ($result) use ($config) {
                $result['type_text'] = !empty($config[$result['type']]) ? $config[$result['type']] : '';
                return $result;
            });
        $this->result($list, 0, '查询完成');
    }

    public function RiderApply()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'mobile' => 'require',
                'password' => 'require',
                'name' => 'require',
                'cards' => 'require',
                'positive' => 'require',
                'negative' => 'require',
                'street' => 'require'
            ], [
                'mobile.require' => '手机号不能为空',
                'password.require' => '密码不能为空',
                'name.require' => '名称不能为空',
                'cards.require' => '身份证号不能为空',
                'positive.require' => '身份证正面不能为空',
                'negative.require' => '身份证反面不能为空',
                'street.require' => '街道ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                $this->result([], 1, '联系电话格式不正确');
            }
            $data['password'] = md5(md5($data['password']));
            $street = (new Region())->where(['id' => $data['street'], 'level' => 4])->find();
            if (empty($street)) {
                $this->result([], 1, '街道ID错误');
            }
            $area = (new Region())->where(['id' => $street['parent_id'], 'level' => 3])->find();
            if (empty($area)) {
                $this->result([], 1, '区域编号错误');
            }
            $data['area'] = $area['area_code'] ?? 0;
            $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
            if (empty($city)) {
                $this->result([], 1, '城市编号错误');
            }
            $data['city'] = $city['area_code'] ?? 0;
            $province = (new Region())->where(['id' => $city['parent_id'], 'level' => 1])->find();
            if (empty($province)) {
                $this->result([], 1, '省份编号错误');
            }
            $data['province'] = $province['area_code'] ?? 0;
            $riderList = (new RiderList())->where(['user_id' => $this->request->user_id])->find();
            if (!empty($riderList)) {
                $Ridercount = (new RiderStreet())->where(['riderid' => $riderList['id'], 'status' => 2])->count();
                if ($Ridercount > 0) {
                    $this->result([], 1, '您已申请街道成功，如需继续申请请前往骑手端申请');
                }
                $riderid = $riderList['id'] ?? 0;
                $RiderStreet = (new RiderStreet())->where(['riderid' => $riderList['id']])->find();
                if (!empty($RiderStreet) && $RiderStreet['status'] == 1 && $RiderStreet['street'] != $street['id']) {
                    $this->result([], 0, '不可以同时申请多个街道，请等待其它街道审核完成');
                }
                if (!empty($RiderStreet) && $RiderStreet['status'] == 2 && $RiderStreet['street'] == $street['id']) {
                    $this->result([], 0, '您已是该区域骑手，无须重复申请');
                }
            }
            $save = [
                'user_id' => $this->request->user_id,
                'mobile' => $data['mobile'],
                'password' => $data['password'],
                'name' => $data['name'],
                'cards' => $data['cards'],
                'positive' => $data['positive'],
                'negative' => $data['negative']
            ];
            Db::startTrans();
            try {
                if (!empty($riderList)) {
                    (new RiderList())->allowfield(true)->save($save, ['id' => $riderList['id']]);
                } else {
                    $riderid = (new RiderList())->insertGetId($save);
                }
                if (!empty($RiderStreet)) {
                    (new RiderStreet())->where('id', $RiderStreet['id'])->update([
                        'riderid' => $riderid,
                        'provinceid' => $data['province'],
                        'cityid' => $data['city'],
                        'areaid' => $data['area'],
                        'street' => $data['street'],
                        'status' => 1
                    ]);
                } else {
                    (new RiderStreet())->insert([
                        'riderid' => $riderid,
                        'provinceid' => $data['province'],
                        'cityid' => $data['city'],
                        'areaid' => $data['area'],
                        'street' => $data['street'],
                        'status' => 1
                    ]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '申请失败，请重试');
            }
            $this->result([], 0, '申请成功，待审核');
        } else {
            $list = (new RiderList())->field('user_id,password', true)->where(['user_id' => $this->request->user_id])->find();
            if (!empty($list)) {
                $riderstreet = (new RiderStreet())->where(['riderid' => $list['id']])->find();
                if (!empty($riderstreet)) {
                    $list['province'] = $riderstreet['provinceid'];
                    $list['city'] = $riderstreet['cityid'];
                    $list['area'] = $riderstreet['areaid'];
                    $list['street'] = $riderstreet['street'];
                    $list['province_text'] = (new Region())->where(['area_code' => $riderstreet['provinceid']])->value('name');
                    $list['city_text'] = (new Region())->where(['area_code' => $riderstreet['cityid']])->value('name');
                    $list['area_text'] = (new Region())->where(['area_code' => $riderstreet['areaid']])->value('name');
                    $list['street_text'] = (new Region())->where(['id' => $riderstreet['street']])->value('name');
                    $list['status'] = $riderstreet['status'];
                }
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function  message()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'message' => 'require',
                'mobile' => 'require',
                'messtype' => 'require'
            ], [
                'message.require' => '反馈信息不能为空',
                'mobile.require' => '联系电话不能为空',
                'messtype.require' => '反馈类型不能为空',

            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['type'] = 1;
            $data['user_id'] = $this->request->user_id;
            $res = (new Message())->allowfield(true)->save($data);
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败');
        } else {
            $list = (new Message())->order('id desc');
            $list = $list->where(['user_id' =>  $this->request->user_id, 'type' => 1])
                ->field('message,reply,created')
                ->paginate(20, false, ['query' => $this->request->param()]);
            $this->result($list, 0, '查询完成');
        }
    }

    public function set_partner()
    {
        $this->result([], 1, '通道关闭');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'data' => 'require',
            ], [
                'data.require' => '数据参数不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $datarr = json_decode($data['data'], true);
            if (empty($datarr)) {
                $this->result([], 1, '数据格式错误');
            }
            $areaid = (new Users())->where('id', $this->request->user_id)->value('areaid');
            $areaid = !empty($areaid) ? $areaid : 0;
            if ($areaid <= 0) {
                $this->result([], 1, '您还不是区域代理');
            }
            $savearr = [];
            $insertarr = [];
            foreach ($datarr as $datas) {
                if (empty($datas['id'])) {
                    $this->result([], 1, '数据参数错误');
                }
                if (!isset($datas['price'])) {
                    $this->result([], 1, '请输入价格');
                }
                $catesons = (new CateSons())->where('id', $datas['id'])->find();
                if (empty($catesons)) {
                    $this->result([], 1, '分类信息不存在');
                }
                //判断需要更新的数据和需要插入的数据
                $catesons = (new AreaPrice())->where(['catsonsid' => $datas['id'], 'streetid' => $areaid])->find();
                if (empty($catesons)) {
                    $insertarr[] = [
                        'catsonsid' => $datas['id'],
                        'areaid' => $areaid,
                        'price' => round($datas['price'], 2)
                    ];
                } else {
                    $savearr[] = [
                        'id' => $catesons['id'],
                        'price' => round($datas['price'], 2)
                    ];
                }
            }
            if (empty($insertarr) && empty($savearr)) {
                $this->result([], 1, '更改信息为空');
            }
            Db::startTrans();
            try {
                if (!empty($insertarr)) {
                    (new AreaPrice())->insertAll($insertarr);
                }
                if (!empty($savearr)) {
                    (new AreaPrice())->allowfield(true)->saveAll($savearr);
                }
                Db::commit();
            } catch (\Exception $e) {
                dump($e->getMessage());
                Db::rollback();
                $this->result([], 1, '修改失败，请重试');
            }
            $this->result([], 0, '修改成功');
        } else {
            $this->result([], 1, '通道关闭');
            $cate = $this->request->get('cate/d', 0);
            //获取当前会员所属区域
            $areaid = (new Users())->where('id', $this->request->user_id)->value('areaid');
            $areaid = !empty($areaid) ? $areaid : 0;
            $list = (new CateSons())->where('cate', $cate)->field('id,name')->select();
            foreach ($list as $lists) {
                $lists['price'] = (new AreaPrice())->where(['catsonsid' => $lists['id'], 'areaid' => $areaid])->value('price');
                $lists['price'] = !empty($lists['price']) ? $lists['price'] : 0;
            }
            $this->result($list, 0, '查询完成');
        }
    }
}
